package com.sp.socket;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 客户端, 发送"hello, server" 给服务端, 然后接收到服务端返回的"hello, client"并打印出来, 使用字符流
 */
public class SocketTCP03Client {
    public static void main(String[] args) throws IOException {
        //1. 连接服务端(IP+端口)
        //连接本机的9999端口, 如果连接成功, 返回Socket对象
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        System.out.println("客户端 socket返回: " + socket.getClass());

        //2. 连接上后, 生成Socket, 通过socket.getOutputStream()
        //得到和socket对象关联的输出对象
        OutputStream outputStream = socket.getOutputStream();

        //3. 通过输出流, 写入数据到数据通道, 使用字符流
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write("hello, server 字符流");
        bufferedWriter.newLine();//插入一个换行符, 表示写入的内容结束, 注意,
        bufferedWriter.flush();//如果使用的字符流, 需要手动刷新, 否则数据不会写入数据通道


        //4. 读取服务端发送的IO
        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String s = bufferedReader.readLine();
        System.out.println(s);

        //5. 关闭流对象和socket, 避免资源浪费
        bufferedReader.close();
        bufferedWriter.close();
        socket.close();
        System.out.println("客户端退出");

    }
}
